import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, Form, Input, InputNumber, Modal, Row, Select, AutoComplete} from 'antd';
import validator from '../../utils/validator';
import debounce from 'lodash/debounce';
const FormItem = Form.Item;
const R = require("ramda");
const dateFormat = 'YYYY-MM-DD';
const orderChargeInfo = Form.create()(class OrderChargeInfo extends React.Component {
    constructor(props) {
        super(props);
        this.handleQuery = debounce(this.handleQuery, 800); //去抖
        this.state = {
            open: false,
            id: undefined,      
            feeType: null,
            addStatus: false, //是否变更新增
            poundage: false, //是否财务自己录入的手续费
            template:false,
            disabled: false
        }
    }


    handleOpen = (id, feeType, addStatus,template, poundage, disabled) => {
        this.setState({ open: true,id, feeType, addStatus,template, poundage, disabled });
    }


    handleCancel = () => {
        this.props.orderCharge.dataSource = {};
        this.setState({ open: false });
        this.props.form.resetFields();
    }

    handleSelect = (value)=>{
        this.props.form.setFieldsValue({ rate: value === "CNY" ? "1": undefined })
    }

    handleQuery = (nameOrCusNo) => {
        if(this.state.feeType === '1'){
            this.props.dispatch({ type: 'company/getListByNameAndCusNo', payload: { nameOrCusNo } });
        }else{
            this.props.dispatch({ type: 'supplier/getSupplierList', payload: { supplier: nameOrCusNo } });
        }
    }

    handleConfirm = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            let data = R.omit(['quotePrice', 'quotePriceCny'])(values);
            data.id = this.props.orderCharge.dataSource && this.props.orderCharge.dataSource.id ? this.props.orderCharge.dataSource.id : null;
            data.orderId = this.props.orderId;
            data.type = this.state.feeType;     
            data.status = this.state.addStatus ? "5" : "1";
            data.status = this.state.poundage ? "2" : data.status;
            data.check = true;
            data.paymentId = this.props.paymentId;
            data.poundage = this.state.poundage ? "1" : "0";
            values.id = this.state.id;
            values.type = this.state.feeType;
            if (!R.equals(R.pick(Object.keys(values), this.props.orderCharge.dataSource), values)) {
                this.props.dispatch({
                    type: R.isNil(data.id) ? 'orderCharge/createOdCharge' : 'orderCharge/updateOdCharge',
                    payload: {
                        ...data,
                        onSuccess: () => {
                            this.handleCancel();
                            if (this.props.refreshList) this.props.refreshList();
                            if (this.props.fetchDetail) this.props.fetchDetail(this.props.receiptId, this.props.orderId);
                            if (this.props.onCalculation) this.props.onCalculation(undefined ,this.state.feeType, values, undefined);
                            if (this.props.fetchPaymentDetail) this.props.fetchPaymentDetail(this.props.paymentId);
                        }
                    }
                })
            } else this.handleCancel();
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        let formItemLayout2 = { labelCol: { sm: { span: 4 } }, wrapperCol: { sm: { span: 19 } } };

        let dataSource = this.props.orderCharge.dataSource ? this.props.orderCharge.dataSource : {};
        let feeItemList = this.props.feeItem.feeItemList ? this.props.feeItem.feeItemList : [];
        // let supplierList = this.props.supplier.supplierList ? this.props.supplier.supplierList : [];
        // let companyList = this.props.company.companyList ? this.props.company.companyList : [];
        // let unitList = this.state.feeType === '1' ? companyList : supplierList;
        // let settlementUnitName = [];
        // unitList.map(item => { settlementUnitName.push(item.companyName); })
        // settlementUnitName = Array.from(new Set(settlementUnitName));

        let quotePrice = this.props.form.getFieldValue("fee") && this.props.form.getFieldValue("count") ? this.props.form.getFieldValue("fee") * this.props.form.getFieldValue("count") : 0;
        quotePrice = Math.round(quotePrice * 10000) / 10000;

        let quotePriceCny = this.props.form.getFieldValue("rate") && quotePrice ? this.props.form.getFieldValue("rate") * quotePrice : 0;
        quotePriceCny = Math.round(quotePriceCny * 10000) / 10000;

        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this)} style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this)}>{this.props.disabled ? "关闭" : "取消"}</Button>
        ];
        return (
            <Modal maskClosable={false} visible={this.state.open} width={850} title={"费用详情"} confirmLoading={this.props.loading} onCancel={this.handleCancel.bind(this)} footer={footer}>
                <Form>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="费用项目" hasFeedback>
                                {getFieldDecorator('feeItemId', {
                                    rules: [{
                                        required: true, message: '请选择费用项目'
                                    }],
                                    initialValue: (R.isNil(dataSource.feeItemId) || R.isEmpty(dataSource.feeItemId)) ? undefined : dataSource.feeItemId + ""
                                })(
                                    <Select style={{ width: '100%' }} disabled={this.state.disabled} showSearch placeholder="可通过输入关键字搜索"
                                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                        {
                                            !R.isNil(feeItemList) ? feeItemList.map(item => {
                                                return (<Select.Option value={item.id + ""} key={item.id + ""}>{item.name + "[" + item.code + "]"}</Select.Option>);
                                            }) : ''
                                        }
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="币种" hasFeedback>
                                {getFieldDecorator('currency', {
                                    rules: [{
                                        required: true, message: '请选择币种',
                                    }],
                                    initialValue: dataSource.currency
                                })(
                                    <Select disabled={this.state.disabled} onChange={this.handleSelect.bind(this)}>
                                        <Select.Option value="CNY">人民币[CNY]</Select.Option>
                                        <Select.Option value="USD">美元[USD]</Select.Option>
                                        <Select.Option value="HKD">港币[HKD]</Select.Option>
                                    </Select>
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="单价" hasFeedback>
                                {getFieldDecorator('fee', {
                                    rules: [{
                                        required: true, message: '请输入单价'
                                    }],
                                    initialValue: dataSource.fee
                                })(
                                    <InputNumber disabled={this.state.disabled} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="数量" hasFeedback>
                                {getFieldDecorator('count', {
                                    rules: [{
                                        required: true, message: '请输入数量',
                                        pattern: validator.DECIMAL2.pattern, message: validator.DECIMAL2.message
                                    }],
                                    initialValue: dataSource.count
                                })(
                                    <InputNumber disabled={this.state.disabled} min={0} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="合计" hasFeedback>
                                {getFieldDecorator('quotePrice', {
                                    initialValue: quotePrice
                                })(
                                    <InputNumber disabled={true} style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="汇率" hasFeedback>
                                {getFieldDecorator('rate', {
                                    rules: [{
                                        required: true, message: '请输入汇率'
                                    }],
                                    initialValue: dataSource.rate
                                })(
                                    <InputNumber disabled={this.props.form.getFieldValue("currency") === "CNY" ? true : this.state.disabled} min={0} max={999999} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="人民币合计" hasFeedback>
                                {getFieldDecorator('quotePriceCny', {
                                    initialValue: quotePriceCny
                                })(
                                    <InputNumber disabled={true} maxLength="11" style={{ width: '100%' }} />
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="结算单位" hasFeedback>
                                {getFieldDecorator('settlementUnit', {
                                    rules: [{
                                        required: true, message: '请选择结算单位'
                                    }],
                                    initialValue: dataSource.settlementUnit ? dataSource.settlementUnit + "" : undefined
                                })(
                                    // <Select style={{ width: '100%' }} disabled={this.state.disabled || this.state.poundage} showSearch placeholder="可通过输入关键字搜索" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                                    //     {
                                    //         !R.isNil(unitList) ? unitList.map(item => {
                                    //             return (<Select.Option value={item.id + ""} key={item.id + ""}>{this.state.feeType === "1" ? item.companyname : item.supplierCode}</Select.Option>);
                                    //         }) : ''
                                    //     }
                                    // </Select>
                                    <AutoComplete maxLength="200" style={{ width: '100%' }} 
                                                  allowClear backfill
                                                  disabled={this.state.disabled || this.state.poundage}
                                                  dataSource={this.state.feeType === '1' ? this.props.company.settlementUnitName : this.props.supplier.settlementUnitName}
                                                  onChange={this.handleQuery.bind(this)}
                                    />
                                    )}
                            </FormItem>
                        </Col>
                    </Row>
                     <Row>
                        <Col span={24}>
                            <FormItem {...formItemLayout2} label="备注" hasFeedback>
                                {getFieldDecorator('memo', {
                                    initialValue: dataSource.memo
                                })(
                                    <Input disabled={this.state.disabled} maxLength="200" />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </Modal >
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.orderCharge, orderCharge: state.orderCharge, feeItem: state.feeItem, supplier: state.supplier, company: state.company
    };
}

export default connect(mapStateToProps)(orderChargeInfo);